package com.kuaifu.autofare.controller.web.api;

import com.alibaba.fastjson.JSONObject;
import com.kuaifu.autofare.bean.model.WechatTemplateMsg;
import com.kuaifu.autofare.bean.model.WxTemplate;
import com.kuaifu.autofare.bean.vo.req.UserReqVo;
import com.kuaifu.autofare.common.config.Global;
import com.kuaifu.autofare.common.utils.*;
import com.kuaifu.autofare.common.web.BaseController;
import com.kuaifu.autofare.service.IWxTemplateService;
import com.kuaifu.autofare.service.template.TemplateMessageAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by mocaijin on 21/12/2017.
 */
@Controller
@RequestMapping("api")
public class WxServiceApi extends BaseController {

    @Autowired
    private IWxTemplateService wxTemplateService;

    /**
     * 绑定手机,车牌
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping("notifyTempMsg")
    public String notifyTempMsg(final Integer userId, final String templateKey) {
        LogUtils.debug(JSONObject.toJSONString(getRequest().getParameterMap()));
        final String appId = getRequest().getParameter("appId");
        final String openId = getRequest().getParameter("openId");

        new Thread(new Runnable() {
            @Override
            public void run() {


                WxTemplate wxTemplate = new WxTemplate();
                wxTemplate.setAppId(appId);
                wxTemplate.setTemplateKey(templateKey);
                try {
                    wxTemplate = wxTemplateService.get(wxTemplate);

                    TemplateMessageAction templateMessageAction = SpringContextHolder.getBean(wxTemplate.getBeanName());
                    WechatTemplateMsg wechatTemplateMsg = templateMessageAction.processMessage(userId);

                    wechatTemplateMsg.setTemplate_id(wxTemplate.getTemplateId());
                    wechatTemplateMsg.setTouser(openId);
                    if (StringUtils.isBank(wechatTemplateMsg.getUrl())) {
                        wechatTemplateMsg.setUrl(wxTemplate.getUrl());
                    }
                    String jsonData = JSONObject.toJSONString(wechatTemplateMsg);
                    LogUtils.debug("jsonData:" + jsonData);
                    String WX_SEND_TEMPLATE_URL = Global.getWxSendTemplateUrl();
                    LogUtils.debug("WX_SEND_TEMPLATE_URL:" + WX_SEND_TEMPLATE_URL);
                    Map<String, Object> params=new HashMap<>();
                    params.put("jsonData",jsonData);
                    HttpRequestUtil.httpClientGet(WX_SEND_TEMPLATE_URL,params);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();


        return "ok";

    }

}
